process.on('exit', function (code) {
	console.log(code)
});
process.stdin.setEncoding('utf8');

process.stdout.write("......\n");
process.stdout.write("请输入运行模式");
process.stdin.on('data', (input) => {
	input = input.toString().trim();
	if (true) {
		const express = require("express"),
			app = express(),
			Gpio = require('onoff').Gpio,
			path = require("path"),
			os = require('os');

		app.use("/", express.static(path.join(__dirname, "public")));
		app.use("/appleOn", express.static(path.join(__dirname, "public/appleOn")));
		app.use("/appleOff", express.static(path.join(__dirname, "public/appleOff")));
		app.use('/static', express.static('static'));

		let TimeNum = 0;
		const led = new Gpio(16, 'out'),
			LanIP = os.networkInterfaces().wlan0[0].address;

		Mode(input);

		function Mode(adminMode) {
			if (adminMode === "1") {

				function detectionTime() { // power on self test
					let hours = new Date().getHours();
					if (hours < 17) {
						led.writeSync(0);
						console.log("now is turn off LED Time");
					} else if (hours > 17) {
						led.writeSync(1);
						console.log("now is turn on LED Time");
					}
				}
				detectionTime();
				setInterval(function () {
					TimeNum = TimeNum + 1; //console.log(TimeNum);
					if (TimeNum === 300) { //5 min is shutdown
						TimeNum = 0;
						detectionTime();
					}
				}, 1000);
			}

			if (adminMode === "0") {
				console.log("Welcome To DevelopMode")
				led.writeSync(1);
			}
		}

		function gpioState(urlPath) {
			if (urlPath === "/on") {
				led.writeSync(1);
			}
			if (urlPath === "/off") {
				led.writeSync(0);
			}
		}

		app.get("/on", function (req, res) {
			gpioState(req.path);
			res.json("ON");
			//console.log(led.readSync());
			//console.log(led.direction());
		});

		app.get("/off", function (req, res) {
			gpioState(req.path);
			res.json("OFF");
		});

		app.get("/appleOn/on", function (req, res) {
			led.writeSync(1);
			res.json("ON");
		});

		app.get("/appleOff/off", function (req, res) {
			led.writeSync(0);
			res.json("OFF");
		});

		app.get("/state", function (req, res) {
			let state = led.readSync();
			console.log(state);
			res.json(state);
		});

		let server = app.listen(3000, LanIP, () => {
			let host = server.address().address;
			let port = server.address().port;
			console.log('Example app listening at http://%s:%s', host, port);
		});
	}
})